package com.voxel.sense.infomsg.module.message;

import com.example.com.common.factory.data.DbDataSource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cyy.example.com.facotry.data.BaseDbRepository;
import cyy.example.com.facotry.model.db.MessageModle;
import cyy.example.com.facotry.net.helper.DbHelper;

/**
 * Created by ChenYiYao on 2018/12/4.
 * des : 消息模块的仓库
 */
public class MsgRepository extends BaseDbRepository<MessageModle> implements DbDataSource<MessageModle> {
    private int mMaxCount = 1000;
    private int mDeleteCount = 200; //数量达到上限后，删除的条数

    @Override
    public void load(SucceedCallback<List<MessageModle>> callback, int reqId) {
        super.load(callback, reqId);
        DbHelper.QueryAll(MessageModle.class);
    }

    @Override
    protected boolean isRequired(MessageModle modle) {
        return true;
    }

    @Override
    protected boolean isRequiredCallbackBefore(List<MessageModle> datas) {
        if (datas == null) return true;

        Collections.sort(datas, new Comparator<MessageModle>() {
            @Override
            public int compare(MessageModle o1, MessageModle o2) {
                return (int) (o2.getTime() - o1.getTime());
            }
        });

        //数据超过一定数据，则进行删除部分数据
        if (datas != null && datas.size() > mMaxCount) {
            deleteFirstPartData(datas);
            return false;
        }
        return true;
    }

    protected void deleteTable() {
        DbHelper.getInstance().deleteAll(MessageModle.class);
    }


    /**
     * 删除最时间最久的200条数据
     * 最开始时间
     *
     * @param list
     */
    public void deleteFirstPartData(List<MessageModle> list) {
        //超过1000条后，删除最后两百条
        List<MessageModle> modleList = new ArrayList<>();
        if (list != null && list.size() >= mMaxCount)
            for (int i = list.size() - 1; i >= mMaxCount - mDeleteCount; i--) {
                modleList.add(list.get(i));
            }
        DbHelper.getInstance().deleteMultObject(MessageModle.class, modleList);
    }


}
